package net.tycmc.cty.ctyms.timejob.function.jsonToExcel;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import net.tycmc.bulb.common.util.StringUtil;
import net.tycmc.cty.ctyms.timejob.function.excel.ExportHandlers2007;

import org.codehaus.jackson.map.ObjectMapper;
/**
 * 将文件中的Json格式数据转换到excel，支持多文件合并
 * 文件1G以内，内存2G及以上，3分钟
 * @author suhe
 *
 */
public class JsonListMap {
	private List<Map<String, Object>> titles = new ArrayList<Map<String, Object>>();
	private List<Map<String, Object>> tempTitle = new ArrayList<Map<String, Object>>();
	private List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
	private static JsonListMap instance;
	public static JsonListMap getInstance(){
			synchronized(JsonListMap.class){
				instance = new JsonListMap();
			}
		return instance;
	}
	/**
	 * 将输入的文件转换成excel文件输出（支持多文件）
	 * @param files 文件数组
	 * @param os	输出方式
	 * @throws Exception
	 */
	public  void jsonToExcel(String[] files,OutputStream os)throws Exception {
		/*清空数据**/
		this.titles.clear();
		this.tempTitle.clear();
		this.datas.clear();
		
		//先写入公共信息标题部分
		Map<String, Object> m1 = new HashMap<String, Object>();
		m1.put("head", "车牌号");
		Map<String, Object> m2 = new HashMap<String, Object>();
		m2.put("head", "采集时间");
		Map<String, Object> m3 = new HashMap<String, Object>();
		m3.put("head", "采集类型");
		titles.add(m1);
		titles.add(m2);
		titles.add(m3);
		for (int i = 0; i < files.length; i++) {//支持多文件写入，循环文件名
			File file = new File(files[i]);
			//读入文件
			InputStreamReader in = new InputStreamReader(new FileInputStream(file),"UTF-8");
			BufferedReader br = new BufferedReader(in);
			String tempString = null;
			StringBuffer sbBuffer = new StringBuffer();
			int count = 0;
			int stat = 0;
			//对读入的文件进行读取
			//转换的字符串以 [ 开头，以 ] 结尾，所以在读第一行之前加[,在结尾加 ]
			while ((tempString = br.readLine()) != null) {
				if (tempString.length() > 0) {
					if (count == 1999) {//每当读取行数达到这个数据，转换一次
						sbBuffer.append(tempString + "]");
						readJson2List(sbBuffer.toString());
						sbBuffer = new StringBuffer();
						count = 0;
						stat = 1;
					} else if (count == 0) {
						if (stat == 0) {
							sbBuffer.append("[" + tempString);
						} else {
							//去掉开头的","号(因为除了第一行，每个开头都有",")
							sbBuffer.append("["+ tempString.substring(1, tempString.length()));
						}
						count++;
					} else {
						sbBuffer.append(tempString);
						count++;
					}
				}
			}
			if (count != 0) {//最后sbBuffer不为空，转换一次
				readJson2List(sbBuffer.toString() + "]");
			}
			sbBuffer = new StringBuffer();
		}
		try {
			ExportHandlers2007 eh = ExportHandlers2007.getInstance();
			eh.exportHandlers(titles, datas, "head", "head", os);
//			ExportHandlers2007.getInstance().exportHandlers(titles, datas,
//					"head", "head", os);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("输出异常");
		}
	}
	/**
	 * 将json字符串文件文件转换为Excel文件，并回传文件内容的时间范围
	 * @throws Exception 
	 **/
	public String[] toExcelAndGetTimeBucket(String[] files,OutputStream os) throws Exception{
		//调用json转换为Excel接口
		this.jsonToExcel(files, os);
		String startTime = "";
		String endTime = "";
//		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		for(Map<String,Object> map:this.datas){
			if(!StringUtil.isValid(startTime)&&!StringUtil.isValid(endTime)){
				startTime = map.get("采集时间").toString();
				endTime = map.get("采集时间").toString();
			}else{
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				try {
					if(formatter.parse(startTime).getTime()>formatter.parse(map.get("采集时间").toString()).getTime()){
						startTime = map.get("采集时间").toString();
					}else{
						if(formatter.parse(endTime).getTime()<formatter.parse(map.get("采集时间").toString()).getTime()){
							endTime = map.get("采集时间").toString();
						}
					}
				} catch (ParseException e) {
					continue;
//					e.printStackTrace();
				}
				/*
				if(startTime.compareTo(map.get("采集时间").toString())>0){
					startTime = map.get("采集时间").toString();
				}else{
					if(endTime.compareTo(map.get("采集时间").toString())<0){
						endTime = map.get("采集时间").toString();
					}
				}*/
			}
		}
		return new String[]{startTime,endTime};		
	}
	/**
	 * 將字符串转换成List<Map<>>格式，进行处理
	 * @param s
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	private  void readJson2List(String s)throws Exception {
		ObjectMapper objectMapper = new ObjectMapper();// 
			// 将Json格式字符串转换
			List<LinkedHashMap<String, Object>> listLine = objectMapper.readValue(s, List.class);
			s = null;
			// 对每个Line对象进行取值
			for (int i = 0; i < listLine.size(); i++) {
				Map<String, Object> map = listLine.get(i);
				Map<String, Object> dataMap = new HashMap<String, Object>();//用变量来存放自己需要的信息
				//先取得公共部分的信息
				dataMap.put("车牌号", map.get("lineName"));
				dataMap.put("采集时间", map.get("lineTime"));
				dataMap.put("采集类型", map.get("lineType"));
				//数据部分的信息
				LinkedHashMap<String, Object> paraDataMap = (LinkedHashMap<String, Object>) map.get("paraData");
				if (paraDataMap.size() > 0) {//如果数据存在，进行读取；不存在，跳过
					List<Map<String, Object>> listdata = (ArrayList<Map<String, Object>>) paraDataMap.get("data");
					for (int d = 0; d < listdata.size(); d++) {
						Map<String, Object> tempdataMap = (Map<String, Object>) listdata.get(d);
						String temps = "" + tempdataMap.get("dataName") + "("+ tempdataMap.get("dataUnit") + ")";
						String id = "" + tempdataMap.get("dataID");
						// 判断标题id列表中是否有这个id，如果有就将标志变量置1，并跳出循环；如果遍历到最后没有就加入到当前标题列表中，
						int stat = 0;//起标识作用
						for (int z = 0; z< tempTitle.size(); z++) {
							Map<String, Object> title = tempTitle.get(z);
							if (title.containsValue(id)) {// 如果有此标题，跳出循环
								stat = 1;
								break;
							}
						}
						if (stat == 0) {// 如果这个dataId前面没有，加入到标题列表
							Map<String, Object> maptitle = new HashMap<String, Object>();
							maptitle.put("head", temps);
							titles.add(maptitle);//增加到标题list中
							Map<String, Object> tempt = new HashMap<String, Object>();
							tempt.put("id", id);
							tempTitle.add(tempt);//增加到临时标题list
						}
						dataMap.put(temps, tempdataMap.get("dataValue"));//将数据信息保存下来
					}
				}
				datas.add(dataMap);//增加到数据list中
			}
			listLine = null;
	}
	/*public static void main(String[] args) {
		// File file = new File("E:/下载数据文件/20130817_冀ATY003.txt");
		try {
			String outFileName = "E:/下载数据文件/123456.xlsx";
			File fileOut = new File(outFileName);
			OutputStream os = new FileOutputStream(fileOut, false);// 输出方式
			String[] ss ={"E:/下载数据文件/20130817_冀ATY003.txt","E:/下载数据文件/20130817_冀ATY003.txt"}; 
			
			
			JsonListMap.getInstance().jsonToExcel(ss,os);
		} catch (Exception e) {
			System.out.println(e);
		}
	}*/
	public static void main(String[] args) {
		String s1="";
		String s2="1";
		System.out.println(s1.compareTo(s2));
	}
}
